<template>
  <div class="app-container">
    <el-form
      ref="form"
      :inline="true"
      :model="formData"
      class="demo-form-inline"
    >
      <el-form-item label="客户名称">
        <el-input
          v-model="formData.name"
          placeholder="请输入客户名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="客户电话">
        <el-input
          v-model="formData.phone"
          placeholder="请输入客户电话"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button class="create" type="primary" @click="create">创建</el-button>

    <el-table :data="list" style="width: 100%">
      <el-table-column prop="id" label="ID" width="180"> </el-table-column>
      <el-table-column prop="name" label="客户名称" width="120">
      </el-table-column>
      <el-table-column prop="phone" label="客户电话" width="120">
      </el-table-column>

      <el-table-column prop="promotionOrderNum" label="推广订单" width="120">
      </el-table-column>

      <el-table-column prop="promotionProfit" label="推广收益" width="120">
      </el-table-column>

      <el-table-column prop="promotionNum" label="推广用户" width="120">
      </el-table-column>

      <el-table-column label="客户地址" width="150">
        <template slot-scope="scope" width="180">
          <span
            >{{ scope.row.provinces }}{{ scope.row.country }}{{ scope.row.city
            }}{{ scope.row.address }}</span
          >
        </template>
      </el-table-column>

      <el-table-column prop="cardName" label="身份证姓名" width="120">
      </el-table-column>

      <el-table-column prop="cardNumber" label="身份证号码" width="180">
      </el-table-column>

      <el-table-column prop="bankCardNumber" label="银行卡号" width="180">
      </el-table-column>

      <el-table-column prop="shareRatio" label="比例"> </el-table-column>

      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1" type="success">代理</el-tag>
          <el-tag v-if="scope.row.status == 0" type="default">非代理</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="备注"> </el-table-column>
      <el-table-column prop="updateBy" label="操作人" width="120">
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="edit(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="queryParams.total > 0"
      :total="queryParams.total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getListData"
    />

    <el-dialog
      title="提示设置"
      :visible.sync="dialogVisible"
      width="800px"
      center
    >
      <el-form
        ref="formDialog"
        :rules="rules"
        :model="dialogForm"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item line label="姓名" prop="name">
              <el-select
                style="width: 100%"
                v-model="dialogForm.name"
                filterable
                remote
                :disabled="!!dialogForm.id"
                reserve-keyword
                placeholder="请输入客户电话搜索"
                :remote-method="remoteMethod"
                :loading="loading"
                @change="handleCustomerChange"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input
                disabled
                v-model="dialogForm.phone"
                placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item line label="区域" prop="provinces">
              <el-cascader
                style="width: 100%"
                :options="regionData"
                v-model="selectedOptions"
                @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item line label="详细地址" prop="address">
              <el-input
                v-model="dialogForm.address"
                placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item line label="身份证姓名" prop="cardName">
              <el-input
                v-model="dialogForm.cardName"
                placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="cardNumber">
              <el-input
                v-model="dialogForm.cardNumber"
                placeholder="请输入身份证"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行卡号" prop="bankCardNumber">
              <el-input
                v-model="dialogForm.bankCardNumber"
                placeholder="请输入银行卡号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="比例" prop="shareRatio">
              <el-input
                v-model="dialogForm.shareRatio"
                placeholder="请输入比例"
              >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理">
              <el-switch
                v-model="dialogForm.status"
                active-value="1"
                inactive-value="0"
                active-color="#13ce66"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="dialogForm.remark"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRegionDistributorList,
  getCustomerList,
  updateRegionDistributor,
  saveRegionDistributor,
  updateRegionDistributorStatus,
} from "@/api/customer/index";
import { codeToText, regionData } from "element-china-area-data";
const defaultFormData = {
  userId: "",
  status: "1",
  shareRatio: "",
  remark: "",
  provinces: "",
  phone: "",
  country: "",
  city: "",
  cardNumber: "",
  cardName: "",
  bankCardNumber: "",
  address: "",
};
export default {
  name: "Index",
  data() {
    return {
      queryParams: {
        page: 0,
        pageSize: 10,
        total: 0,
      },
      formData: {
        name: "",
        phone: "",
      },
      list: [],
      codeToText,

      dialogVisible: false,
      dialogForm: {},
      options: [],
      loading: false,
      selectedOptions: [],
      regionData,
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        provinces: [{ required: true, message: "请选择省份", trigger: "blur" }],
        country: [{ required: true, message: "请选择国家", trigger: "blur" }],
        city: [{ required: true, message: "请选择城市", trigger: "blur" }],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        cardNumber: [
          { required: true, message: "请输入身份证", trigger: "blur" },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "请输入正确的身份证",
          },
        ],
        bankCardNumber: [
          { required: true, message: "请输入银行卡号", trigger: "blur" },
          {
            pattern: /^([1-9])\d{14,18}$/,
            message: "请输入正确的银行卡号",
          },
        ],
        cardName: [
          { required: true, message: "请输入身份证姓名", trigger: "blur" },
          { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: "请输入正确的姓名" },
        ],
        shareRatio: [
          { required: true, message: "请输入比例", trigger: "blur" },
          // 1 ~ 100 正整数
          {
            pattern: /^([1-9]\d?|100)$/,
            message: "请输入1-100的正整数",
          },
        ],
      },
    };
  },
  created() {
    this.getListData({
      page: 1,
      limit: 10,
    });
  },
  methods: {
    getListData({ page, limit }) {
      getRegionDistributorList(
        this.queryParams,
        page || this.queryParams.page + 1,
        limit
      ).then(({ data }) => {
        this.list = data.records;
        this.queryParams.total = data.total;
        this.queryParams.page = data.current;
        this.queryParams.limit = data.size;
      });
    },
    onSearch() {
      this.queryParams = {
        ...this.queryParams,
        ...this.formData,
      };
      this.getListData({
        page: 1,
        limit: 10,
      });
    },
    reset() {
      this.formData = {
        name: "",
        phone: "",
      };
    },
    create() {
      this.dialogForm = {
        ...defaultFormData,
      };
      this.selectedOptions = [];
      this.dialogVisible = true;
    },
    edit(row) {
      const [provinces, country, city] = row.extendInfo.split("-");
      this.dialogForm = {
        ...row,
        name: row.id,
        provinces,
        country,
        city,
        status: row.status.toString(),
      };
      this.selectedOptions = [provinces, country, city];
      this.options = [
        {
          label: `${row.name}(${row.phone})`,
          value: row.id,
        },
      ];
      // console.log(this.dialogForm, "this.dialogForm");
      this.dialogVisible = true;
    },
    handleCustomerChange(value) {
      if (value) {
        const item = this.options.find((item) => item.value === value);
        this.dialogForm.phone = item.label.split("(")[1].split(")")[0];
        this.dialogForm.userId = value.id;
        // console.log(item, "item");
      } else {
        this.dialogForm.phone = "";
        this.dialogForm.userId = "";
      }
    },
    handleChange() {
      this.dialogForm.provinces = this.selectedOptions[0];
      this.dialogForm.city= this.selectedOptions[1];
      this.dialogForm.country= this.selectedOptions[2];
    },
    submitForm() {
      this.$refs.formDialog.validate(async (valid) => {
        if (valid) {
          const user = this.options.find(
            (item) => item.value === this.dialogForm.name
          );
          const params = {
            ...this.dialogForm,
            userId: user.id,
            name: user.name,
            extendInfo: `${this.dialogForm.provinces}-${this.dialogForm.country}-${this.dialogForm.city}`,
            provinces: codeToText[this.dialogForm.provinces],
            country: codeToText[this.dialogForm.country],
            city: codeToText[this.dialogForm.city],
          };
          const fn = params.id
            ? updateRegionDistributor
            : saveRegionDistributor;
          await fn(params);
          this.dialogVisible = false;
          this.getListData({
            page: 1,
            limit: 10,
          });
        } else {
          return false;
        }
      });
    },
    async remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        try {
          const { data } = await getCustomerList({
            phone: query,
          });

          this.options = data.records.map((item) => {
            return {
              label: `${item.name}(${item.phone})`,
              value: item.id,
              ...item,
            };
          });
          this.loading = false;
        } catch (err) {
          // console.log(err);
          this.loading = false;
        }
      } else {
        this.options = [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.create {
  margin-bottom: 20px;
}
</style>
